package com.base.controller.utils.CZB;

import com.alibaba.fastjson.JSONObject;
import com.base.comm.CommUrls;
import com.base.helper.WebHelper;

public class LocationUtils {
    private static double EARTH_RADIUS = 6371.393;
    private static double rad(double d)
    {
        return d * Math.PI / 180.0;
    }

    /**
     * 计算两个经纬度之间的距离(普通算法，对CPU的性能负载高)
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
    {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.abs(Math.pow(Math.sin(a/2),2) +
                Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2))));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 1000);
        return s;
    }
    /**
     *  @Date: 2020/5/16 18:45
     *  @Description:
     *  根据经纬度获取省份代码
     */
    public static String code(String lon,String lat){
        String url="https://restapi.amap.com/v3/geocode/regeo";
        String param="?key="+ CommUrls.GDMAPKEY+"&location="+lon+","+lat;
        String data= WebHelper.PostData(url+param,null,null,null);
        JSONObject jsonObject=JSONObject.parseObject(data);
        Object rec=jsonObject.get("regeocode");
        JSONObject regeocode=JSONObject.parseObject(rec.toString());
        Object addressComponent=regeocode.get("addressComponent");
        String code=JSONObject.parseObject(addressComponent.toString()).getString("adcode");
        String retrunCode=code.substring(0,2)+"0000";
        return retrunCode;
    }
    /**
     *  @Date: 2020/5/16 17:10
     *  @Description:
     *  Haversine 计算方法，优化CPU的计算
     */
    public static double distHaversineRAD(double lat1, double lon1, double lat2, double lon2) {
        double hsinX = Math.sin((lon1 - lon2) * 0.5);
        double hsinY = Math.sin((lat1 - lat2) * 0.5);
        double h = hsinY * hsinY +
                (Math.cos(lat1) * Math.cos(lat2) * hsinX * hsinX);
        return 2 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h)) * 6367000;
    }

//    /**
//     *  @Date: 2020/5/16 17:10
//     *  @Description:
//     *  Haversine 计算方法，转化为x,y,z三轴坐标，进行计算（美团大佬的计算方式，减正弦和余弦的使用）
//     */
//    public static double distanceSimplify(double lat1, double lng1, double lat2, double lng2) {
//        double dx = lng1 - lng2; // 经度差值
//        double dy = lat1 - lat2; // 纬度差值
//        double b = (lat1 + lat2) / 2.0; // 平均纬度
//        double Lx = toRadians(dx) * 6367000.0* Math.cos(toRadians(b)); // 东西距离
//        double Ly = 6367000.0 * toRadians(dy); // 南北距离
//        return Math.sqrt(Lx * Lx + Ly * Ly);  // 用平面的矩形对角距离公式计算总距离
//}


    public static void main(String[] args) {
        System.out.println(LocationUtils.GetDistance(29.490295,106.486654,29.615467,106.581515));
    }
}
